package com.zg.common.web.config;

import com.zg.common.web.aop.TokenInterceptor;
import lombok.AllArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;

/**
 * WebMvc配置
 * @author Zxb
 */
@Configuration
@AllArgsConstructor
public class WebMvcConfig implements WebMvcConfigurer {

    private ApplicationContext context;
    private ExcludePathProperties excludePathProperties;
    private TokenInterceptor tokenInterceptor;

    /**
     * 配置静态资源
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");
    }

    /**
     * 配置参数处理器
     */
    @Override
    public void addArgumentResolvers(@Nonnull List<HandlerMethodArgumentResolver> resolvers) {
        Map<String, HandlerMethodArgumentResolver> beans = context.getBeansOfType(HandlerMethodArgumentResolver.class);
        beans.forEach((name, bean) -> resolvers.add(bean));
    }

    /**
     * 配置参数转换器
     */
    @Override
    public void addFormatters(@Nonnull FormatterRegistry registry) {
        @SuppressWarnings("rawtypes")
        Map<String, Converter> beans = context.getBeansOfType(Converter.class);
        beans.forEach((name, bean) -> registry.addConverter(bean));
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenInterceptor)
                .excludePathPatterns("/")
                .excludePathPatterns("/error")
                .excludePathPatterns("/favicon.ico")
                .excludePathPatterns(excludePathProperties.getPath().split(","))
                .excludePathPatterns("/mock/**")
                .excludePathPatterns("/nacos/**")
                .excludePathPatterns("/swagger-ui/**", "/swagger-resources/**", "/webjars/**", "/v2/**", "/v3/**", "/doc.html")
                .addPathPatterns("/**");
    }
}
